package com.wxmp.wxapi.service.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.wxmp.core.util.DateUtil;
import com.wxmp.wxapi.service.IAccountService;
import com.wxmp.wxapi.util.*;
import com.wxmp.wxcms.domain.Account;
import com.wxmp.wxcms.domain.AccountFans;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoField;
import java.time.temporal.TemporalAdjusters;
import java.util.*;

import static com.wxmp.wxapi.util.HolidayConstant.*;

/**
 * @Description
 * @Author cys
 * @Date 2022/10/8 11:56 AM
 */
public abstract class AbstractAccountService implements IAccountService {

    @Override
    public void pushMorningMessage(AccountFans accountFans, String templateId, Account account) {
        //1，配置
        WxMpService wxMpService = Pusher.getWxStorage(account);
        //2,推送消息
        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                .toUser(accountFans.getOpenId())
                .templateId(templateId)
                //.url("https://30paotui.com/")//点击模版消息要访问的网址
                .build();
        //3,如果是正式版发送模版消息，这里需要配置你的信息
        //        templateMessage.addData(new WxMpTemplateData("name", "value", "#FF00FF"));
        //                templateMessage.addData(new WxMpTemplateData(name2, value2, color2));
        //填写变量信息，比如天气之类的
        JSONObject todayWeather = Tianqi.getNanjiTianqi(accountFans.getDistrict(), account.getBaiduak());
        String textDay = todayWeather.getString("text_day");
        String content = "";
        if ("雷阵雨".equals(textDay)) {
            content = "~出门带上雨伞哦!!!";
        }
        String tianqi = textDay + content;
        templateMessage.addData(new WxMpTemplateData("riqi", todayWeather.getString("date") + "  " + todayWeather.getString("week"), "#00BFFF"));
        templateMessage.addData(new WxMpTemplateData("tianqi", tianqi, "#00FFFF"));
        templateMessage.addData(new WxMpTemplateData("text_night", todayWeather.getString("text_night"), "#00FFFF"));
        templateMessage.addData(new WxMpTemplateData("wc_day", todayWeather.getString("wc_day"), "#00FFFF"));
        templateMessage.addData(new WxMpTemplateData("wd_day", todayWeather.getString("wd_day"), "#00FFFF"));
        templateMessage.addData(new WxMpTemplateData("wd_night", todayWeather.getString("wd_night"), "#00FFFF"));
        templateMessage.addData(new WxMpTemplateData("wenDu", todayWeather.getString("low") + "~" + todayWeather.getString("high") + "℃", "#173177"));
        templateMessage.addData(new WxMpTemplateData("caihongpi", CaiHongPi.getCaiHongPi(account.getChpkey(), CaiHongPi.morningUrl), "#FF69B4"));
        String nowDate = DateUtil.getNowDate();
        String periodDate = StringUtils.isNotBlank(accountFans.getPeriodDate()) ? accountFans.getPeriodDate() : nowDate;
        templateMessage.addData(new WxMpTemplateData("jq", LocalDate.parse(periodDate).plusDays(30).toString(), "#FF69B4"));
        String ym = DateUtil.daysBetween(periodDate, DateUtil.changeDateTOStr3(new Date()));
        templateMessage.addData(new WxMpTemplateData("ym", ym, "#FF69B4"));

        String loveDate = StringUtils.isNotBlank(accountFans.getLoveDate()) ? accountFans.getLoveDate() : nowDate;

        templateMessage.addData(new WxMpTemplateData("lianai", DateUtil.daysBetween(loveDate, DateUtil.changeDateTOStr3(new Date())), "#FF1493"));

        String birthday = StringUtils.isNotBlank(accountFans.getBirthday()) ? accountFans.getBirthday() : nowDate;

        templateMessage.addData(new WxMpTemplateData("shengri", DateUtil.getSriDay(birthday), "#FFA500"));
        JSONObject object = CaiHongPi.getEveryday(account.getChpkey(), CaiHongPi.everydayUrl);
        templateMessage.addData(new WxMpTemplateData("en", object.getString("content"), "#C71585"));
        templateMessage.addData(new WxMpTemplateData("zn", object.getString("note"), "#C71585"));
        //templateMessage.addData(new WxMpTemplateData("jiehun",JiNianRi.getJieHun()+""));
        // templateMessage.addData(new WxMpTemplateData("linzhen",JiNianRi.getLinZhen()+"","#FF6347"));

        String beizhu = "";
        int anInt = Integer.parseInt(ym);
        if (DateUtil.getLianAi(loveDate)) {
            beizhu = "今天是恋爱纪念日！";
        } else if (DateUtil.getShengRi(birthday)) {
            beizhu = "今天是你的生日！";
        }
        if (anInt > 28 || anInt < 5) {
            if (StringUtils.isNotBlank(beizhu)) {
                beizhu = beizhu + "~";
            }
            beizhu = beizhu + "经期期间记得随身准备好姨妈巾哦!";
        }
        templateMessage.addData(new WxMpTemplateData("beizhu", beizhu, "#FF0000"));
        try {
            wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void pushNightMessage(AccountFans accountFans, String templateId, Account account) {
        WxMpService wxStorage = Pusher.getWxStorage(account);
        //2,推送消息
        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                .toUser(accountFans.getOpenId())
                .templateId(templateId)
                //.url("https://30paotui.com/")//点击模版消息要访问的网址
                .build();

        templateMessage.addData(new WxMpTemplateData("caihongpi", CaiHongPi.getCaiHongPi(account.getChpkey(), CaiHongPi.nightUrl), "#FF69B4"));
        try {
            wxStorage.getTemplateMsgService().sendTemplateMsg(templateMessage);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void pushNoonMessage(AccountFans accountFans, String templateId, Account account) {
        WxMpService wxStorage = Pusher.getWxStorage(account);
        //2,推送消息
        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                .toUser(accountFans.getOpenId())
                .templateId(templateId)
                //.url("https://30paotui.com/")//点击模版消息要访问的网址
                .build();

        templateMessage.addData(new WxMpTemplateData("chifan", "到点啦,准备进食能量和午休了哦!", "#FF69B4"));
        templateMessage.addData(new WxMpTemplateData("qiaomen", CaiHongPi.getCaiHongPi(account.getChpkey(), CaiHongPi.qiaomenUrl), "#FF0000"));
        templateMessage.addData(new WxMpTemplateData("jiankang", CaiHongPi.getCaiHongPi(account.getChpkey(), CaiHongPi.healthUrl), "#FF0000"));
        try {
            wxStorage.getTemplateMsgService().sendTemplateMsg(templateMessage);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void pushLoafMessage(AccountFans accountFans, String templateId, Account account) {
        //1，配置
        WxMpService wxMpService = Pusher.getWxStorage(account);
        //2,推送消息
        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                .toUser(accountFans.getOpenId())
                .templateId(templateId)
                .build();
        Date now = new Date();
        //日期
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("MM月dd日");
        LocalDate nowDate = LocalDate.now();
        String localDateStr = nowDate.format(fmt);
        //上午还是下午
        int index = new GregorianCalendar().get(GregorianCalendar.AM_PM);
        int year = nowDate.getYear();
        //距离周末还有
        DayOfWeek dayOfWeek = nowDate.getDayOfWeek();
        //下个星期六
        LocalDate nextSaturday = nowDate.with(TemporalAdjusters.next(DayOfWeek.SATURDAY));

        //距离元旦还有
        Date wewYearDay = HolidayUtil.getHoliday(NEWYEARDAY, year);
        //距离春节还有
        Date springFestival = HolidayUtil.getHoliday(CHINESENEWYEARGREGORIANFESTIVAL, year);
        //距离清明节还有
        Date pureBrightness = HolidayUtil.getHoliday(QINGMINGFESTIVAL, year);
        //距离劳动节还有
        Date laborDay = HolidayUtil.getHoliday(LABORDAY, year);
        //距离端午节还有
        Date dragonBoatFestival = HolidayUtil.getHoliday(DRAGONBOATGREGORIANFESTIVAL, year);
        //距离中秋节还有
        Date midAutumnFestival = HolidayUtil.getHoliday(MIDAUTUMNGREGORIANFESTIVAL, year);
        //距离国庆节还有
        Date nationalDay = HolidayUtil.getHoliday(NATIONALDAY, year);
        //214
        Date valentineDay2_14 = HolidayUtil.getHoliday(VALENTINE_DAY_2_14, year);
        //7-7
        Date nationalDay7_7 = HolidayUtil.getHoliday(VALENTINE_DAY_7_7, year);
        templateMessage.addData(new WxMpTemplateData("date", localDateStr));
        templateMessage.addData(new WxMpTemplateData("date2", index == 0 ? "上午" : "下午"));
        templateMessage.addData(new WxMpTemplateData("weekend", DayOfWeek.SATURDAY.equals(dayOfWeek) ? getRandomBlessingWords(zhouMoList).trim() : DateUtil.localDateCompare(nowDate.plusDays(1), nextSaturday) == 0 ? "明天就周末啦！" : "距离周末还有: " + DateUtil.localDateCompare(nowDate.plusDays(1), nextSaturday) + "天", "#FF0000"));
        templateMessage.addData(new WxMpTemplateData("wew_year_day", DateUtils.isSameDay(now, wewYearDay) ? getRandomBlessingWords(yuanDanList).trim() :  DateUtil.localDateCompare(nowDate, DateUtil.dateToLocalDate(wewYearDay)) == 0 ? "明天就元旦啦！": "距离元旦还有: " + DateUtil.localDateCompare(nowDate, DateUtil.dateToLocalDate(wewYearDay)) + "天", "#FF7F00"));
        templateMessage.addData(new WxMpTemplateData("spring_festival", DateUtils.isSameDay(now, springFestival) ? getRandomBlessingWords(chunJieList).trim() : DateUtil.localDateCompare(nowDate, DateUtil.dateToLocalDate(springFestival)) == 0 ? "今天大年30啦！" : "距离春节还有: "+ DateUtil.localDateCompare(nowDate, DateUtil.dateToLocalDate(springFestival))+"天", "#6bddc2"));
        templateMessage.addData(new WxMpTemplateData("pure_brightness",DateUtils.isSameDay(now, pureBrightness) ? getRandomBlessingWords(qingMingList).trim() : DateUtil.localDateCompare(nowDate, DateUtil.dateToLocalDate(pureBrightness)) == 0 ? "明天就清明节啦！" : "距离清明节还有: "+ DateUtil.localDateCompare(nowDate, DateUtil.dateToLocalDate(pureBrightness))+"天", "#00FF00"));
        templateMessage.addData(new WxMpTemplateData("labor_day", DateUtils.isSameDay(now, laborDay) ? getRandomBlessingWords(laoDongList).trim() : DateUtil.localDateCompare(nowDate, DateUtil.dateToLocalDate(laborDay)) == 0 ? "明天就劳动节啦！" : "距离劳动节还有: "+ DateUtil.localDateCompare(nowDate, DateUtil.dateToLocalDate(laborDay))+"天" , "#00FFFF"));
        templateMessage.addData(new WxMpTemplateData("dragon_boat_festival", DateUtils.isSameDay(now, dragonBoatFestival) ? getRandomBlessingWords(duanWuList).trim() : DateUtil.localDateCompare(nowDate, DateUtil.dateToLocalDate(dragonBoatFestival)) == 0 ? "明天就端午节啦！" : "距离端午节还有: "+ DateUtil.localDateCompare(nowDate, DateUtil.dateToLocalDate(dragonBoatFestival))+"天", "#0000FF"));
        templateMessage.addData(new WxMpTemplateData("mid_autumn_festival", DateUtils.isSameDay(now, midAutumnFestival) ? getRandomBlessingWords(zhongqiuList).trim() : DateUtil.localDateCompare(nowDate, DateUtil.dateToLocalDate(midAutumnFestival)) == 0 ? "明天就中秋节啦！" : "距离中秋节还有: "+ DateUtil.localDateCompare(nowDate, DateUtil.dateToLocalDate(midAutumnFestival))+"天", "#8B00FF"));
        templateMessage.addData(new WxMpTemplateData("national_day", DateUtils.isSameDay(now, nationalDay) ? getRandomBlessingWords(guoQingList).trim() : DateUtil.localDateCompare(nowDate, DateUtil.dateToLocalDate(nationalDay)) == 0 ? "明天就国庆节啦！" : "距离国庆节还有: "+ DateUtil.localDateCompare(nowDate, DateUtil.dateToLocalDate(nationalDay))+"天", "#ff66ff"));
        templateMessage.addData(new WxMpTemplateData("valentine_Day1", DateUtils.isSameDay(now, valentineDay2_14) ? getRandomBlessingWords(qingRenList).trim():  DateUtil.localDateCompare(nowDate, DateUtil.dateToLocalDate(valentineDay2_14)) == 0 ? "明天就情人节啦！" : "距离情人节还有: "+DateUtil.localDateCompare(nowDate, DateUtil.dateToLocalDate(valentineDay2_14))+"天", "#ff6699"));
        templateMessage.addData(new WxMpTemplateData("valentine_Day2", DateUtils.isSameDay(now, nationalDay7_7) ? getRandomBlessingWords(qiXiList).trim() : DateUtil.localDateCompare(nowDate, DateUtil.dateToLocalDate(nationalDay7_7)) == 0 ? "明天就七夕啦！" : "距离七夕节还有: "+ DateUtil.localDateCompare(nowDate, DateUtil.dateToLocalDate(nationalDay7_7))+"天", "#ff66cc"));


        try {
            wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void pushWarmReminderMessage(AccountFans accountFans, String templateId, Account account) {
        LocalDate nowDate = LocalDate.now();
        Date now = new Date();
        //1，配置
        WxMpService wxMpService = Pusher.getWxStorage(account);
        //2,推送消息
        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                .toUser(accountFans.getOpenId())
                .templateId(templateId)
                .build();
        //5号发工资
        LocalDate payday5 = nowDate.with(ChronoField.DAY_OF_MONTH, 5);
        //10号发工资
        LocalDate payday10 = nowDate.with(ChronoField.DAY_OF_MONTH, 10);
        //15号发工资
        LocalDate payday15 = nowDate.with(ChronoField.DAY_OF_MONTH, 15);
        //20号发工资
        LocalDate payday20 = nowDate.with(ChronoField.DAY_OF_MONTH, 20);
        //25号发工资
        LocalDate payday25 = nowDate.with(ChronoField.DAY_OF_MONTH, 25);
        //月底发工资
        LocalDate paydayLast = nowDate.with(TemporalAdjusters.lastDayOfMonth());
        //新冠爆发日
        LocalDate yiQingDay = LocalDate.of(2019, 12, 16);
        templateMessage.addData(new WxMpTemplateData("clew", "关闭房间插座电源", "#ff0000"));
        templateMessage.addData(new WxMpTemplateData("payday5", DateUtils.isSameDay(now, DateUtil.localDateToDate(payday5)) ? "啦啦啦！【5号发工资】的今天发工资啦！" : "距离【5号发工资】还有：" + DateUtil.differ(nowDate, payday5) + "天"));
        templateMessage.addData(new WxMpTemplateData("payday10", DateUtils.isSameDay(now, DateUtil.localDateToDate(payday10)) ? "啦啦啦！【10号发工资】的今天发工资啦！" : "距离【10号发工资】还有: " + DateUtil.differ(nowDate, payday10) + "天"));
        templateMessage.addData(new WxMpTemplateData("payday15", DateUtils.isSameDay(now, DateUtil.localDateToDate(payday15)) ? "啦啦啦！【15号发工资】的今天发工资啦！" : "距离【15号发工资】还有：" + DateUtil.differ(nowDate, payday15) + "天"));
        templateMessage.addData(new WxMpTemplateData("payday20", DateUtils.isSameDay(now, DateUtil.localDateToDate(payday20)) ? "啦啦啦！【20号发工资】的今天发工资啦！" : "距离【20号发工资】还有：" + DateUtil.differ(nowDate, payday20) + "天"));
        templateMessage.addData(new WxMpTemplateData("payday25", DateUtils.isSameDay(now, DateUtil.localDateToDate(payday25)) ? "啦啦啦！【25号发工资】的今天发工资啦！" : "距离【25号发工资】还有：" + DateUtil.differ(nowDate, payday25) + "天"));
        templateMessage.addData(new WxMpTemplateData("payLastDay", DateUtils.isSameDay(now, DateUtil.localDateToDate(paydayLast)) ? "啦啦啦！【月底发工资】的今天发工资啦！" : "距离【月底发工资】还有：" + DateUtil.differ(nowDate, paydayLast) + "天"));
        templateMessage.addData(new WxMpTemplateData("num", DateUtil.localDateCompare(yiQingDay, nowDate) + "", "#FF0000"));

        try {
            wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private static final List<String> zhouMoList = new ArrayList<>();
    private static final List<String> yuanDanList = new ArrayList<>();
    private static final List<String> chunJieList = new ArrayList<>();
    private static final List<String> qingMingList = new ArrayList<>();
    private static final List<String> laoDongList = new ArrayList<>();
    private static final List<String> duanWuList = new ArrayList<>();
    private static final List<String> zhongqiuList = new ArrayList<>();
    private static final List<String> guoQingList = new ArrayList<>();
    private static final List<String> qingRenList = new ArrayList<>();
    private static final List<String> qiXiList = new ArrayList<>();

    static {
        InputStream zhouMoInputStream = CaiHongPi.class.getClassLoader().getResourceAsStream("zhoumo.txt");
        InputStream yuanDanInputStream = CaiHongPi.class.getClassLoader().getResourceAsStream("yuandan.txt");
        zhouMoList.addAll(read(zhouMoInputStream));
        yuanDanList.addAll(read(yuanDanInputStream));
        chunJieList.add("天生笑笑动我心，爱你一生是真心，别人追你我担心，害我工作不专心，看见你时就开心，永远对你最真心，一生一世不变心，世界未日一颗心。宝贝，新年快乐呀！");
        qingMingList.add("柳丝飘飘，牵动悠远的思念；雨滴点点，敲开心海的涟漪；去无声的是流金岁月；永不变的是人间真情。清明时节，少点哀思，多点真情，让爱在身边流动。");
        laoDongList.add("十分快乐在心里，一年四季好时机，十分幸福在梦里，日理万机不稀奇，十分美梦在手里，患难与共挡风雨，十分浪漫在眼里，有情有爱不分离，十分友爱在故里，同心协力舟共济，十分想你在五一，祝你开心又如意！");
        duanWuList.add("端午伴着五谷，幸福填满一屋；糖馅裹着幸福，吃下没有苦楚；香粽艾叶同煮，走过漫漫长路；“粽”有情“艾”有意，一生和你共度。");
        zhongqiuList.add("月儿圆圆天边挂，梦想圆圆都成真，荷叶圆圆水中立，情谊缘缘永不变。宝，中秋快乐！");
        guoQingList.add("这一生，最浪漫的事情就是与你一同度过每一个春夏秋冬，一同经历每一个节日，一直到老；今天国庆到了，最重要的事情就是和你生活在一起。一起度过伟大的国庆节");
        qingRenList.add("未来有多远，我们一起走过，路途多漫长，我们一起走过，有你的每一天都是晴天。");
        qiXiList.add("点点飞星传情，片片纤云弄巧。脉脉月华如练，悠悠又见鹊桥。天淡银河垂地，相思无计回避。纵然千山万里，寄我心中情语：爱你永不变!七夕愉快!");
    }

    private static List<String> read(InputStream inputStream) {
        List<String> list = Lists.newArrayList();
        try (BufferedReader br = new BufferedReader(new InputStreamReader(Objects.requireNonNull(inputStream)))) {
            StringBuilder str = new StringBuilder();
            String temp;
            while ((temp = br.readLine()) != null) {
                if (!StringUtils.isEmpty(temp)) {
                    str.append("\r\n").append(temp);
                } else {
                    list.add(str.toString());
                    str = new StringBuilder();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }


    public static String getRandomBlessingWords(List<String> list) {
        Random random = new Random();
        return list.get(random.nextInt(list.size()));
    }


    public static void main(String[] args) {
        LocalDate localDate = LocalDate.now();
        System.out.println(localDate.plusDays(24));

    }




}
